package com.example.zzx.dovebook.booksearch.searchhistory

import android.app.Application
import android.content.ContentValues
import android.database.Cursor
import com.example.zzx.dovebook.database.AppDatabaseHelper

class HistoryManager(application: Application) {

    private val dbHelper = AppDatabaseHelper.getInstance(application)

    fun getHistory(): List<String>? {
        var cursor: Cursor? = dbHelper.query(AppDatabaseHelper.SEARCH_TABLE_NAME,
            null, arrayOf("content"), null, null, "updateAt desc")
        if (cursor == null || !cursor.moveToFirst()) {
            return null
        }
        val historyList = mutableListOf<String>()
        do {
            historyList.add(cursor.getString(0))
        } while (cursor.moveToNext())
        return historyList
    }

    fun deleteHistory(content: String): Boolean {
        return dbHelper.delete(AppDatabaseHelper.SEARCH_TABLE_NAME,
            null, "content = ? ", arrayOf(content)) !=
                AppDatabaseHelper.DELETE_ERROR
    }

    fun updateHistory(content: String): Boolean {
        val contentValue = ContentValues()
        contentValue.put("updateAt", System.currentTimeMillis())
        return dbHelper.update(AppDatabaseHelper.SEARCH_TABLE_NAME, null,
            contentValue, "content = ?", arrayOf(content)) != AppDatabaseHelper.UPDATE_ERROR
    }

    fun addHistory(content: String): Boolean {
        val cursor = dbHelper.query(AppDatabaseHelper.SEARCH_TABLE_NAME, null, null,
            "content = ? ", arrayOf(content), null)
        //表示此项记录已经存在，则只需更新时间即可
        if (cursor.count != 0) {
            updateHistory(content)
            return false
        }
        val contentValue = ContentValues()
        contentValue.put("content", content)
        contentValue.put("updateAt", System.currentTimeMillis())
        dbHelper.insert(AppDatabaseHelper.SEARCH_TABLE_NAME, null, contentValue)
        return true
    }
}